﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Common;
using HIWSystem.Models;

namespace HIWSystem.ViewModel
{
    public class ENDViewModel :ViewModelBase
    {
        #region 属性
        TrackingEntity trackingEntity = null;
        //用于判断是不是第一次触发过滤，是则备份原始数据源
        private bool isFirstFilterPN = true;
        //当没有输入内容时恢复到备份的原始数据源
        ObservableCollection<PartNumberEntity> backupPNs = null;
        private string sn="";
        /// <summary>
        /// 序列号
        /// </summary>
        public string SN
        {
            get { return sn; }
            set { sn = value; this.RaisePropertyChanged(() => SN); }
        }
        private int inputCount=0;
        /// <summary>
        /// 已刷数量
        /// </summary>
        public int InputCount
        {
            get { return inputCount; }
            set { inputCount= value; this.RaisePropertyChanged(() => InputCount); }
        }
        private ObservableCollection<string> inputSns;
        /// <summary>
        /// 已刷的序列号
        /// </summary>
        public ObservableCollection<string> InputSns
        {
            get { return inputSns; }
            set { inputSns = value; this.RaisePropertyChanged(() => InputSns); }
        }
        private ObservableCollection<TrackingEntity> snTracking;
        /// <summary>
        /// 序列号测试Log信息
        /// </summary>
        public ObservableCollection<TrackingEntity> SnTracking
        {
            get { return snTracking; }
            set { snTracking = value; this.RaisePropertyChanged(() => SnTracking); }
        }
        private bool txtSnisEnabled= true;
        /// <summary>
        /// 条码输入框是否只读
        /// </summary>
        public bool txtSnIsEnabled
        {
            get { return txtSnisEnabled; }
            set { txtSnisEnabled = value; this.RaisePropertyChanged(() => txtSnIsEnabled); }
        }
        private bool txtSnfocusable=true;
        /// <summary>
        /// 条码框获得鼠标焦点
        /// </summary>
        public bool txtSnFocusable
        {
            get { return txtSnfocusable; }
            set { txtSnfocusable = value; this.RaisePropertyChanged(() => txtSnFocusable); }
        }

        private bool btnSubmitisEnabled=true;
        /// <summary>
        /// 是否启用提交按钮
        /// </summary>
        public bool btnSubmitIsEnabled
        {
            get { return btnSubmitisEnabled; }
            set { btnSubmitisEnabled = value; this.RaisePropertyChanged(() => btnSubmitIsEnabled); }
        }
        private ObservableCollection<PartNumberEntity> pns;
        /// <summary>
        /// 机种实体集合
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }
        private PartNumberEntity selectedPartNumber;
        /// <summary>
        /// 选择的机种实体
        /// </summary>
        public PartNumberEntity SelectedPartNumber
        {
            get { return selectedPartNumber; }
            set { selectedPartNumber = value; this.RaisePropertyChanged(() => SelectedPartNumber); }
        }
        private string pn;
        /// <summary>
        /// 机种
        /// </summary>
        public string PN
        {
            get { return pn; }
            set { pn = value; this.RaisePropertyChanged(() => PN); }
        }
        private bool isOpenComboPNDropDown;
        /// <summary>
        /// 是否展开机种下拉框选项卡
        /// </summary>
        public bool IsOpenComboPNDropDown
        {
            get { return isOpenComboPNDropDown; }
            set { isOpenComboPNDropDown = value; this.RaisePropertyChanged(() => IsOpenComboPNDropDown); }
        }
        private string searchPNText;
        /// <summary>
        /// 机种下拉框中输入的文本内容
        /// </summary>
        public string SearchPNText
        {
            get { return searchPNText; }
            set { searchPNText = value; this.RaisePropertyChanged(() => SearchPNText); }
        }
        //SelectIndex

        private int selectIndex;
        /// <summary>
        /// 机种集合中的下标
        /// </summary>
        public int SelectIndex
        {
            get { return selectIndex; }
            set { selectIndex = value; this.RaisePropertyChanged(() => SelectIndex); }
        }
        #endregion
        #region 命令
        private RelayCommand submitCmd;

        public RelayCommand SubmitCmd
        {
            get 
            {
                if (submitCmd==null)
                {
                    submitCmd = new RelayCommand(Submit);
                }
                return submitCmd; 
            }
            set { submitCmd = value; }
        }
        private RelayCommand snKeyEnterCommand;

        public RelayCommand SNKeyEnterCommand
        {
            get 
            {
                if (snKeyEnterCommand==null)
                {
                    snKeyEnterCommand = new RelayCommand(SnKeyEnterHandler);
                }
                return snKeyEnterCommand;
            }
            set { snKeyEnterCommand = value; }
        }
        private RelayCommand filterPNCmd;
        /// <summary>
        /// 机种过滤
        /// </summary>
        public RelayCommand FilterPNCmd
        {
            get
            {
                if (filterPNCmd == null)
                {
                    filterPNCmd = new RelayCommand(FilterPN);
                }
                return filterPNCmd;
            }
            set { filterPNCmd = value; }
        }
        private RelayCommand loadedPageCmd;

        public RelayCommand LoadedPageCmd
        {
            get {
                loadedPageCmd = loadedPageCmd ?? new RelayCommand(LoadedPage);
                return loadedPageCmd; }
            set { loadedPageCmd = value; }
        }

        #endregion

        #region 方法

        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadedPage()
        {
            //填充机种信息到下拉列表框中
            FillPNsToComboBox();
        }
        /// <summary>
        /// 提交入库数据
        /// </summary>
        private void Submit()
        {
            string inputSn = string.Empty;//录入的SN
            string behindPN = string.Empty;//后台机种信息
            string retMsg = string.Empty;//返回的检测信息
            DataTable dtTracking = new DataTable();//返回的序列号测试Log信息
            trackingEntity = new TrackingEntity();
            //站位开始时间
            trackingEntity.StartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            inputSn = this.SN.Trim().ToUpper();
            this.SN = "";
            //禁用文本框和按钮的可用状态
            this.ControlEnabledState(false);
            if ((inputSn ?? "")=="")
            {
                //启用文本框和按钮的可用状态
                this.ControlEnabledState(true);
                MessageBox.Show("输入的条码不能为空","软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Error);
                return;
            }
            behindPN= BusinessProcess.SnOwnerPN(inputSn);
            if (behindPN!=PN)
            {
                //启用文本框和按钮的可用状态
                this.ControlEnabledState(true);
                MessageBox.Show(string.Format("输入的条码【{0}】不属于机种【{1}】.\r\n请确认输入的信息是否正确?如果正确请切换机种信息.",inputSn,PN), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            retMsg = BusinessProcess.VerifyEndWorkStation(inputSn);
            string[] arrayMsg = new string[2];
            arrayMsg = retMsg.Split('|');
            if (arrayMsg[0] == "NO")
            {
                //启用文本框和按钮的可用状态
                this.ControlEnabledState(true);
                MessageBox.Show(arrayMsg[1], "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            else if(arrayMsg[0]=="OK")
            {
                //初始化Log实体信息
                trackingEntity.Sn = inputSn;
                trackingEntity.Station = "END";
                trackingEntity.Result = "PASS";
                trackingEntity.EquipmentName = Environment.MachineName;
                trackingEntity.StopTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //站位结束时间
                trackingEntity.Actor = LogInInfo.User;
                retMsg = BusinessProcess.AddEndTracking(trackingEntity, out dtTracking);
                arrayMsg = new string[2];
                arrayMsg = retMsg.Split('|');
                if (arrayMsg[0] == "OK")
                {
                    SnTracking = new ObservableCollection<TrackingEntity>();
                    for (int i = 0; i < dtTracking.Rows.Count; i++)
                    {
                        SnTracking.Add(new TrackingEntity
                        {
                            Sn = dtTracking.Rows[i]["Sn"].ToString(),
                            WO = dtTracking.Rows[i]["WO"].ToString(),
                            Station = dtTracking.Rows[i]["Station"].ToString(),
                            Result = dtTracking.Rows[i]["Result"].ToString(),
                            FailDescription = dtTracking.Rows[i]["FailDescription"].ToString(),
                            FailValue = dtTracking.Rows[i]["FailValue"].ToString(),
                            EquipmentName = dtTracking.Rows[i]["EquipmentName"].ToString(),
                            TestSequence = dtTracking.Rows[i]["TestSequence"].ToString(),
                            Actor = dtTracking.Rows[i]["Actor"].ToString()
                        });
                    }
                    this.InputCount += 1;
                    if (InputSns==null)
                        InputSns = new ObservableCollection<string>();
                    InputSns.Add(inputSn+"--"+PN);
                }
                else if(arrayMsg[0]=="NO")
                {
                    MessageBox.Show(arrayMsg[1],"软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Error);
                }
                //启用文本框和按钮的可用状态
                this.ControlEnabledState(true);
            }
        }
        /// <summary>
        /// 控件的可用状态
        /// </summary>
        /// <param name="state">状态</param>
        private void ControlEnabledState(bool state)
        {
            this.txtSnIsEnabled = state;
            this.btnSubmitIsEnabled = state;
            this.txtSnFocusable = true;
        }
        /// <summary>
        /// 条码文本框回车事件处理函数
        /// </summary>
        private void SnKeyEnterHandler()
        {
            Submit();
        }
        /// <summary>
        /// 筛选机种下拉列表框中的数据
        /// </summary>
        private void FilterPN()
        {

            IsOpenComboPNDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterPN)
            {
                backupPNs = new ObservableCollection<PartNumberEntity>();
                backupPNs = PNs;
                isFirstFilterPN = false;
            }
            if (!string.IsNullOrEmpty(SearchPNText))
            {
                IEnumerable<PartNumberEntity> partNumberEntities = PNs.Where(s => s.PN.ToUpper().Contains(SearchPNText.ToUpper()));
                PNs = new ObservableCollection<PartNumberEntity>();
                foreach (var p in partNumberEntities)
                {
                    PNs.Add(p);
                }
            }
            else
            {
                PNs = backupPNs;
            }

        }
        /// <summary>
        /// 填充机种信息
        /// </summary>
        private void FillPNsToComboBox()
        {
            DataTable dtPNs = new DataTable();
            dtPNs = BusinessProcess.GetPNs(EnumPNType.All);
            PNs = new ObservableCollection<PartNumberEntity>();
            PNs.Add(new PartNumberEntity { PN = "无" });
            for (int i = 0; i < dtPNs.Rows.Count; i++)
            {
                PNs.Add(new PartNumberEntity
                {
                    PN = dtPNs.Rows[i]["PartNumber"].ToString()
                });
            }
            SelectIndex = 0;
        }
        #endregion
    }
}
